package org.example.service;

import lombok.RequiredArgsConstructor;
import org.example.dao.BookDao;
import org.example.entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class BookService implements IBookService{

    private final BookDao bookDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public static final String SK_BOOK_KEY = "sk_books";

    @Override
    public List<Book> getAll(Integer secondsSkill) {
        Book book =  new Book();
        book.setSecondsSkill(1);
        return bookDao.findAll(Example.of(book));
    }

    public boolean cacheBook() {
        //查询所有秒杀书籍
        Book b = new Book();
        b.setSecondsSkill(1);
        Example<Book> example = Example.of(b);
        List<Book> list = bookDao.findAll(example);
        //构造bookid->数量的map
        Map<String, String> map = new HashMap<>();
        for (Book book: list){
            map.put(book.getId().toString(), "10");
        }
        stringRedisTemplate.opsForHash().putAll(SK_BOOK_KEY, map);
        return true;
    }

    public boolean clearCache() {
        return stringRedisTemplate.delete(SK_BOOK_KEY).booleanValue();
    }

    public Book findById(Long bookId) {
        return bookDao.findById(bookId).get();
    }

    public void modifyStock(Long bookId, int amount) {
        Book book = this.findById(bookId);
        book.setAmount(book.getAmount() + amount);
        bookDao.save(book);
    }
}
